package com.likou.second_challenge;

import java.util.LinkedList;
import java.util.Queue;

public class q437 {

    public int pathSum(TreeNode root, int targetSum) {
        if (root == null) {
            return 0;
        }

        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        int ans = 0;

        while (!queue.isEmpty()) {
            int size = queue.size();
            while (size > 0) {
                TreeNode poll = queue.poll();
                ans += DFS(poll, targetSum, 0L);
                if (poll.left != null) {
                    queue.offer(poll.left);
                }
                if (poll.right != null) {
                    queue.offer(poll.right);
                }

                size--;
            }
        }

        return ans;
    }

    private int DFS(TreeNode root, int targetSum, long sum) {
        if (root == null) {
            return 0;
        }

        int ans = 0;
        sum += root.val;
        if (sum == targetSum) {
            ans++;
        }

        ans += DFS(root.left, targetSum, sum);
        ans += DFS(root.right, targetSum, sum);

        return ans;
    }

}
